package com.qianniu.napi.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qianniu.napi.common.config.Constants;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/**
 * 调用图灵机器人api接口，获取智能回复内容
 *
 * @author chenxuebin
 */
public class TulingApiProcess {

    private static final Logger logger = LoggerFactory.getLogger(TulingApiProcess.class);

    /**
     * 调用图灵机器人api接口，获取智能回复内容，解析获取自己所需结果
     *
     * @param content
     * @return
     */
    public static String getTulingResult(String content, int searchType, String fromUserName, int httpMethod) {

        logger.debug("start to getTulingResult:content=" + content + " fromUserName=" + fromUserName + " searchType=" + searchType + " httpMethod=" + httpMethod);

        String APIKEY = getRandomKey();
        String result = "";
        if (httpMethod == Constants.HTTP_METHOD_POST) {

            List<NameValuePair> formParams = new ArrayList<NameValuePair>();
            formParams.add(new BasicNameValuePair("key", APIKEY));
            formParams.add(new BasicNameValuePair("info", content.replaceAll(" ", "")));
            formParams.add(new BasicNameValuePair("userid", fromUserName));

            result = HttpUtils.httpPost(Constants.URL_TULING_API, formParams);
            JSONObject json = JSON.parseObject(result);
            result = json.getString("text");

            logger.debug(" getTulingResult result=" + result);

            return result;
        }

        try {
            String INFO = URLEncoder.encode(content, "utf-8");
            String getURL = Constants.URL_TULING_API + "?key=" + APIKEY + "&info=" + INFO;
            JSONObject json = JSON.parseObject(HttpUtils.httpGet(getURL));
            result = json.getString("text");
        } catch (UnsupportedEncodingException e) {
            logger.error("getTulingResult UnsupportedEncodingException error", e);
        } catch (IOException e) {
            logger.error("getTulingResult IOException error", e);
        }

        return result;
    }

    private static String haolingUrl = "http://mobile.9om.com/FRONT/MOBILENO.html";

    /**
     * 调用号令天下接口，获取智能回复内容，解析获取自己所需结果
     *
     * @param mobileNo
     * @return
     */
    public static String getHaoling(String mobileNo) {


        String url = haolingUrl.replace("FRONT", mobileNo.substring(0, 6)).replace("MOBILENO", mobileNo);

        logger.debug("start to getHaoling url=" + url);

        String APIKEY = getRandomKey();
        String result = HttpUtils.httpGet(url);
        Document doc = Jsoup.parse(result);

        Element element = doc.getElementById("center");
        Elements elements = doc.select("#center>div");

        Element tell = element.select(".tell>.detail").get(0);
        logger.debug(tell.html());

        Element info = element.select(".cell>.tips").get(0);
        logger.debug(info.html());
        Element motto = element.select(".cell>.tips").get(1);
        logger.debug(motto.html());


//        return result;
        return info.text();
    }


    private static String getRandomKey() {

        int cout = Constants.tulingKeyList.size();
        Random ran = new Random();
        int index = ran.nextInt(cout);
        return Constants.tulingKeyList.get(index);
//        return RegexUtil.tulingKeyList.get(0);

    }

    /**
     * 调用图灵机器人平台接口
     * 描述：@param args
     * 描述：@throws IOException
     * 作者：herosky
     */
    public static void main(String[] args) throws IOException {
//        String shouji1 = "13799332211";
//        String shouji2 = "137993322";
//
//        System.out.println("shouji1 match ="+ RegexUtil.REGEX_SHOUJIHAO.matcher(shouji1).find());
//        System.out.println("shouji2 match ="+ RegexUtil.REGEX_SHOUJIHAO.matcher(shouji2).find());

        String xingming1 = "程工呀";
        String xingming2 = "2小兵";
        String xingming3 = "好不好呀";
        String xingming4 = "好3不_好 呀*的2d（";


        System.out.println("shouji1 match =" + RegexUtil.REGEX_XINGMING.matcher(xingming1).find());
        System.out.println("shouji2 match =" + RegexUtil.REGEX_XINGMING.matcher(xingming2).find());
        System.out.println("shouji2 match =" + RegexUtil.REGEX_XINGMING.matcher(xingming3).find());

        System.out.println("xingming4 =" + xingming4.replaceAll("吉凶|的|\\s|_|\\W", ""));

        System.out.println("xingming4 \\W=" + xingming4.replaceAll("\\W+", ""));
        System.out.println("xingming4 \\w=" + xingming4.replaceAll("\\w", ""));
        System.out.println("xingming4 \\S=" + xingming4.replaceAll("\\S", ""));
        System.out.println("xingming4 \\s=" + xingming4.replaceAll("\\s", ""));
        System.out.println("xingming4 [^0-9]=" + xingming4.replaceAll("[^0-9]", ""));


//        String content = "孝感市云梦县的天气";
//        content = content.replaceAll("的|省|市|县|旗|镇|区","");
//        Pattern hubei = Pattern.compile("云梦|孝感");
//        Matcher matcher= hubei.matcher(content);
//
////        String city = hubei.matcher(content).group(hubei.matcher(content).end());
//
//        while (matcher.find()){
//            System.out.println("content="+ matcher.group(0));
//        }
//
//        System.out.println("RegexUtil.REGEX_AREA_PREFIX.pattern()="+RegexUtil.REGEX_AREA_PREFIX.pattern());
////        System.out.println("city="+city);
//
//        if(RegexUtil.SESSION_TYPE_MAP.get("123123")!=null
//                &&RegexUtil.SEARCH_TYPE_EXPRESS==RegexUtil.SESSION_TYPE_MAP.get("123123")) {
//            System.out.println("content="+RegexUtil.SESSION_TYPE_MAP.get("123123"));
//        }else{
//            System.out.println(" not exsit ");
//        }

//        String APIKEY = "438cc658c632496fa4dc33511cb2674d";
//        //String INFO = URLEncoder.encode("合肥天气", "utf-8");
//        String INFO = "合肥天气";
//        //String getURL = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO;
//        String getURL = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO;
//        URL getUrl = new URL(getURL);
//        HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
//        connection.connect();
//
//        // 取得输入流，并使用Reader读取
//        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
//        StringBuffer sb = new StringBuffer();
//        String line = "";
//        String result = null;
//        while ((line = reader.readLine()) != null) {
//            sb.append(line);
//        }
//        reader.close();
//        // 断开连接
//        connection.disconnect();
//        System.out.println(sb);
//        JSONObject json;
//        try {
//            json = JSON.parseObject(sb.toString());
//            if("100000".equals(json.get("code").toString()))
//            {
//                result = json.getString("text");
//            }
//            result = new String(result.getBytes(), "UTF-8");
//            logger.debug(result);
//        } catch (Exception e) {
//            logger.error("调用图灵机器人平台接口测试出错",e);
//            e.printStackTrace();
//        }

//        for(int i=0;i<49;i++){
//            List<JokeDO> list = new ArrayList<JokeDO>();
//
//            for(int j=1;j<=100;j++){
//                JokeDO joke = new  JokeDO();
////                joke.setContent(getTulingResult("笑话",0));
//                list.add(joke);
//            }
//        }

//        System.out.println(getTulingResult("成语接龙一心二意",RegexUtil.SEARCH_TYPE_CHENGYU,"12345678",RegexUtil.HTTP_METHOD_POST));
//        System.out.println(getTulingResult("成语接龙牛毛细雨牛毛细雨",RegexUtil.SEARCH_TYPE_CHENGYU,"12345678",RegexUtil.HTTP_METHOD_POST));
//        System.out.println(getTulingResult("成语接龙风鬟雾鬓",RegexUtil.SEARCH_TYPE_CHENGYU,"12345678",RegexUtil.HTTP_METHOD_POST));
//        System.out.println(getTulingResult("成语接龙发的广东省",RegexUtil.SEARCH_TYPE_CHENGYU,"12345678",RegexUtil.HTTP_METHOD_POST));
//        System.out.println(getTulingResult("成语接龙万紫千红",RegexUtil.SEARCH_TYPE_CHENGYU,"12345678",RegexUtil.HTTP_METHOD_POST));
//        System.out.println(getTulingResult("成语接龙事与愿违",RegexUtil.SEARCH_TYPE_CHENGYU,"12345678",RegexUtil.HTTP_METHOD_POST));
//        System.out.println(getTulingResult("成语接龙意气用事",RegexUtil.SEARCH_TYPE_CHENGYU,"12345678",RegexUtil.HTTP_METHOD_POST));
//        System.out.println(getTulingResult("成语接龙成千上万",RegexUtil.SEARCH_TYPE_CHENGYU,"12345678",RegexUtil.HTTP_METHOD_POST));
//        System.out.println(getTulingResult("成语接龙呵呵耐人寻味呵呵",RegexUtil.SEARCH_TYPE_CHENGYU,"12345678",RegexUtil.HTTP_METHOD_POST));

//
//        Redisson client = RedisUtils.getInstance().getRedisson();
////        String beijingtq = "北京天气";
//        String beijingtq = "武汉天气";
//        String value =RedisUtils.getInstance().get(EncryptUtil.md5(beijingtq));
//
//        System.out.println("currentTimeMillis="+System.currentTimeMillis());
//
//        if(Strings.isNullOrEmpty(value)) {
//            String tianqi = getTulingResult(beijingtq, RegexUtil.SEARCH_TYPE_CHENGYU, "12345678", RegexUtil.HTTP_METHOD_GET);
//            RedisUtils.getInstance().set(EncryptUtil.md5(beijingtq), tianqi);
//            System.out.println("tianqi="+tianqi);
//        }else{
//            System.out.println("bucketString="+value);
//        }

    }

}
